package org.etlt.job;

import java.util.ArrayList;
import java.util.List;

public class PkRange {
    /**
     * exclusive (>)
     */
    final private long startPk;
    /**
     * inclusive (<=)
     */
    final private long endPk;

    public PkRange(long startPk, long endPk) {
        if (endPk < startPk)
            throw new IllegalArgumentException("endIndex should be greater than or equal startIndex: " + startPk + "," + endPk);
        this.startPk = startPk;
        this.endPk = endPk;
    }

    public long getStartPk() {
        return startPk;
    }

    public long getEndPk() {
        return endPk;
    }

    public List<PkRange> split(int count) {
        List<PkRange> pkRanges = new ArrayList<>();
        long step = (getEndPk() - getStartPk()) / count;
        long start = getStartPk();
        long end;
        for (int i = 0; i < count; i++) {
            end = start + step;
            if (i + 1 == count) {
                end = getEndPk();
            }
            if (end >= start) {
                PkRange range = new PkRange(start, end);
                start = end;
                pkRanges.add(range);
                if (range.getStartPk() == range.getEndPk())
                    break;
                if (start >= getEndPk())
                    break;
            }
        }
        return pkRanges;
    }

    @Override
    public String toString() {
        return "PkRange[" + startPk + "," + endPk + "]";
    }
}
